//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Permissions;
namespace DotNetNuke.Services.Authentication
{
	public class AuthenticationController
	{
		private static DataProvider provider = DataProvider.Instance();
		private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs)
		{
			return CBO.FillCollection<AuthenticationInfo>(provider.GetAuthenticationServices());
		}
		public static int AddAuthentication(AuthenticationInfo authSystem)
		{
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			objEventLog.AddLog(authSystem, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Log.EventLog.EventLogController.EventLogType.AUTHENTICATION_CREATED);
			return provider.AddAuthentication(authSystem.PackageID, authSystem.AuthenticationType, authSystem.IsEnabled, authSystem.SettingsControlSrc, authSystem.LoginControlSrc, authSystem.LogoffControlSrc, UserController.GetCurrentUserInfo().UserID);
		}
		public static int AddUserAuthentication(int userID, string authenticationType, string authenticationToken)
		{
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			objEventLog.AddLog("userID/authenticationType", userID.ToString() + "/" + authenticationType.ToString(), PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, Log.EventLog.EventLogController.EventLogType.AUTHENTICATION_USER_CREATED);
			return provider.AddUserAuthentication(userID, authenticationType, authenticationToken, UserController.GetCurrentUserInfo().UserID);
		}
		public static void DeleteAuthentication(AuthenticationInfo authSystem)
		{
			provider.DeleteAuthentication(authSystem.AuthenticationID);
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			objEventLog.AddLog(authSystem, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Log.EventLog.EventLogController.EventLogType.AUTHENTICATION_DELETED);
		}
		public static AuthenticationInfo GetAuthenticationService(int authenticationID)
		{
			AuthenticationInfo authInfo = null;
			foreach (AuthenticationInfo authService in GetAuthenticationServices()) {
				if (authService.AuthenticationID == authenticationID) {
					authInfo = authService;
					break;
				}
			}
			if (authInfo == null) {
				return CBO.FillObject<AuthenticationInfo>(provider.GetAuthenticationService(authenticationID));
			}
			return authInfo;
		}
		public static AuthenticationInfo GetAuthenticationServiceByPackageID(int packageID)
		{
			AuthenticationInfo authInfo = null;
			foreach (AuthenticationInfo authService in GetAuthenticationServices()) {
				if (authService.PackageID == packageID) {
					authInfo = authService;
					break;
				}
			}
			if (authInfo == null) {
				return CBO.FillObject<AuthenticationInfo>(provider.GetAuthenticationServiceByPackageID(packageID));
			}
			return authInfo;
		}
		public static AuthenticationInfo GetAuthenticationServiceByType(string authenticationType)
		{
			AuthenticationInfo authInfo = null;
			foreach (AuthenticationInfo authService in GetAuthenticationServices()) {
				if (authService.AuthenticationType == authenticationType) {
					authInfo = authService;
					break;
				}
			}
			if (authInfo == null) {
				return CBO.FillObject<AuthenticationInfo>(provider.GetAuthenticationServiceByType(authenticationType));
			}
			return authInfo;
		}
		public static List<AuthenticationInfo> GetAuthenticationServices()
		{
			return CBO.GetCachedObject<List<AuthenticationInfo>>(new CacheItemArgs(DataCache.AuthenticationServicesCacheKey, DataCache.AuthenticationServicesCacheTimeOut, DataCache.AuthenticationServicesCachePriority), GetAuthenticationServicesCallBack);
		}
		public static AuthenticationInfo GetAuthenticationType()
		{
			AuthenticationInfo objAuthentication = null;
			if (HttpContext.Current != null && HttpContext.Current.Request != null) {
				try {
					objAuthentication = GetAuthenticationServiceByType(HttpContext.Current.Request["authentication"]);
				} catch {
				}
			}
			return objAuthentication;
		}
		public static List<AuthenticationInfo> GetEnabledAuthenticationServices()
		{
			List<AuthenticationInfo> enabled = new List<AuthenticationInfo>();
			foreach (AuthenticationInfo authService in GetAuthenticationServices()) {
				if (authService.IsEnabled) {
					enabled.Add(authService);
				}
			}
			return enabled;
		}
		public static string GetLogoffRedirectURL(PortalSettings settings, HttpRequest request)
		{
			string _RedirectURL = "";
			object setting = UserModuleBase.GetSetting(settings.PortalId, "Redirect_AfterLogout");
			if (Convert.ToInt32(setting) == Null.NullInteger) {
				if (TabPermissionController.CanViewPage()) {
					_RedirectURL = DotNetNuke.Common.Globals.NavigateURL(settings.ActiveTab.TabID);
				} else if (settings.HomeTabId != -1) {
					_RedirectURL = DotNetNuke.Common.Globals.NavigateURL(settings.HomeTabId);
				} else {
					_RedirectURL = DotNetNuke.Common.Globals.GetPortalDomainName(settings.PortalAlias.HTTPAlias, request, true) + "/" + DotNetNuke.Common.Globals.glbDefaultPage;
				}
			} else {
				_RedirectURL = DotNetNuke.Common.Globals.NavigateURL(Convert.ToInt32(setting));
			}
			return _RedirectURL;
		}
		public static void SetAuthenticationType(string value)
		{
			SetAuthenticationType(value, false);
		}
		public static void SetAuthenticationType(string value, bool CreatePersistentCookie)
		{
			try {
				int PersistentCookieTimeout = Config.GetPersistentCookieTimeout();
				HttpResponse Response = HttpContext.Current.Response;
				if (Response == null) {
					return;
				}
				System.Web.HttpCookie cookie = null;
				cookie = Response.Cookies.Get("authentication");
				if ((cookie == null)) {
					if (!String.IsNullOrEmpty(value)) {
						cookie = new System.Web.HttpCookie("authentication", value);
						if (CreatePersistentCookie) {
							cookie.Expires = DateTime.Now.AddMinutes(PersistentCookieTimeout);
						}
						Response.Cookies.Add(cookie);
					}
				} else {
					cookie.Value = value;
					if (!String.IsNullOrEmpty(value)) {
						if (CreatePersistentCookie) {
							cookie.Expires = DateTime.Now.AddMinutes(PersistentCookieTimeout);
						}
						Response.Cookies.Set(cookie);
					} else {
						Response.Cookies.Remove("authentication");
					}
				}
			} catch {
				return;
			}
		}
		public static void UpdateAuthentication(AuthenticationInfo authSystem)
		{
			provider.UpdateAuthentication(authSystem.AuthenticationID, authSystem.PackageID, authSystem.AuthenticationType, authSystem.IsEnabled, authSystem.SettingsControlSrc, authSystem.LoginControlSrc, authSystem.LogoffControlSrc, UserController.GetCurrentUserInfo().UserID);
			Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
			objEventLog.AddLog(authSystem, PortalController.GetCurrentPortalSettings(), UserController.GetCurrentUserInfo().UserID, "", Log.EventLog.EventLogController.EventLogType.AUTHENTICATION_UPDATED);
		}
	}
}
